import CardList from '@/pages/FilmTelevision/CardList';
import styles from '@/pages/Home.less';
import {listFilmTelevisionUsingPOST} from '@/services/otherworldly-station-backend/FilmTelevisionController';
import {Card, Col, Layout, Row, Spin} from 'antd';
import Search from 'antd/es/input/Search';
import {Content} from 'antd/es/layout/layout';
import React, {useEffect, useState} from 'react';
import {ProFormSelect} from "@ant-design/pro-form";

type tabKeyType = 'all' | 'wish' | 'doing' | 'collect';
const FilmTelevision: React.FC = () => {
    const [tabKey, setTabKey] = useState<tabKeyType>('all');
    const [loading, setLoading] = useState<boolean>(false);
    const [isSearching, setIsSearching] = useState<boolean>(false);
    const [wishCount, setWishCount] = useState<number>(0);
    const [doingCount, setDoingCount] = useState<number>(0);
    const [collectCount, setCollectCount] = useState<number>(0);
    const [cardCount, setCardCount] = useState<number>(0);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [searchKey, setSearchKey] = useState<string>('');
    const [wishCardRecords, setWishCardRecords] = useState<API.FilmTelevisionVO[]>([]);
    const [doingCardRecords, setDoingCardRecords] = useState<API.FilmTelevisionVO[]>([]);
    const [collectCardRecords, setCollectCardRecords] = useState<API.FilmTelevisionVO[]>([]);
    const [cardRecords, setCardRecords] = useState<API.FilmTelevisionVO[]>([]);

    const searchCardList = async (
        watchStatus: number,
        pageSize: number,
        current: number,
        value: string,
    ) => {
        setLoading(true);
        listFilmTelevisionUsingPOST({watchStatus, searchKeys: value, pageSize, current})
            .then((res) => {
                if (res.code === 0) {
                    if (watchStatus === 0) {
                        setCardRecords(res.data || []);
                        setCardCount(res.data?.length || 0);
                    } else if (watchStatus === 1) {
                        setWishCardRecords(res.data || []);
                        setWishCount(res.data?.length || 0);
                    } else if (watchStatus === 2) {
                        setDoingCardRecords(res.data || []);
                        setDoingCount(res.data?.length || 0);
                    } else if (watchStatus === 3) {
                        setCollectCardRecords(res.data || []);
                        setCollectCount(res.data?.length || 0);
                    }
                    setSearchKey(value);
                }
            })
            .finally(() => {
                setLoading(false);
            });
    };

    const loadAllData = async (pageSize: number, current: number, type: string) => {
        setLoading(true);
        listFilmTelevisionUsingPOST({pageSize, current, type})
            .then((res) => {
                if (res.code === 0) {
                    let wish = 0,
                        wishRecords: API.FilmTelevisionVO[] = [];
                    let doing = 0,
                        doingRecords: API.FilmTelevisionVO[] = [];
                    let collect = 0,
                        collectRecords: API.FilmTelevisionVO[] = [];
                    res.data?.forEach((record: any) => {
                        if (record.watchStatus === 1) {
                            wish++;
                            wishRecords.push(record);
                        } else if (record.watchStatus === 2) {
                            doing++;
                            doingRecords.push(record);
                        } else if (record.watchStatus === 3) {
                            collect++;
                            collectRecords.push(record);
                        }
                    });
                    setWishCount(wish);
                    setDoingCount(doing);
                    setCollectCount(collect);
                    setWishCardRecords(wishRecords);
                    setDoingCardRecords(doingRecords);
                    setCollectCardRecords(collectRecords);
                    setCardCount(res.data?.length || 0);
                    setCardRecords(res.data || []);
                }
            })
            .finally(() => {
                setLoading(false);
            });
    };

    useEffect(() => {
        loadAllData(20, 1, '');
    }, []);

    const renderChildrenByTabKey = (tabKey: string) => {
        if (tabKey === 'all') {
            return (
                <CardList
                    onSearchData={async (pageSize, current, value) => {
                        await loadAllData(pageSize, current, '');
                    }}
                    currentPage={currentPage}
                    setCurrentPage={(page: number) => setCurrentPage(page)}
                    searchKey={searchKey}
                    records={cardRecords}
                    recordsCount={cardCount}
                />
            );
        } else if (tabKey === 'wish') {
            return (
                <CardList
                    onSearchData={async (pageSize, current, value) => {
                        await loadAllData(pageSize, current, '');
                    }}
                    currentPage={currentPage}
                    setCurrentPage={(page: number) => setCurrentPage(page)}
                    searchKey={searchKey}
                    records={wishCardRecords}
                    recordsCount={wishCount}
                />
            );
        } else if (tabKey === 'doing') {
            return (
                <CardList
                    onSearchData={async (pageSize, current, value) => {
                        await loadAllData(pageSize, current, '');
                    }}
                    currentPage={currentPage}
                    setCurrentPage={(page: number) => setCurrentPage(page)}
                    searchKey={searchKey}
                    records={doingCardRecords}
                    recordsCount={doingCount}
                />
            );
        } else if (tabKey === 'collect') {
            return (
                <CardList
                    onSearchData={async (pageSize, current, value) => {
                        await loadAllData(pageSize, current, '');
                    }}
                    currentPage={currentPage}
                    setCurrentPage={(page: number) => setCurrentPage(page)}
                    searchKey={searchKey}
                    records={collectCardRecords}
                    recordsCount={collectCount}
                />
            );
        }
    };

    const operationTabList = [
        {
            key: 'all',
            tab: (
                <span>
                    全部 {cardCount ? <span style={{fontSize: 14}}>({cardCount})</span> : '(0)'}
                </span>
            ),
        },
        {
            key: 'wish',
            tab: (
                <span>
                    想看 {wishCount ? <span style={{fontSize: 14}}>({wishCount})</span> : '(0)'}
                </span>
            ),
        },
        {
            key: 'doing',
            tab: (
                <span>
                    在看 {doingCount ? <span style={{fontSize: 14}}>({doingCount})</span> : '(0)'}
                </span>
            ),
        },
        {
            key: 'collect',
            tab: (
                <span>
                    看过{' '}
                    {collectCount ? <span style={{fontSize: 14}}>({collectCount})</span> : '(0)'}
                </span>
            ),
        },
    ];
    return (
        <>
            <Layout>
                <div className={styles.searchHeader}>
                    <Search
                        prefix="🔍"
                        style={{verticalAlign: 'middle', width: '65%'}}
                        placeholder="输入关键字搜索我的影片"
                        enterButton="搜索"
                        size="large"
                        allowClear
                        // loading={loading}
                        onSearch={async (value) => {
                            if (!value) {
                                setIsSearching(false);
                                await loadAllData(20, 1, '');
                            } else {
                                // 实现替换全局界面，仅显示卡片列表
                                setIsSearching(true);
                                await searchCardList(0, 20, 1, value);
                            }
                        }}
                    />
                </div>
                <Content>
                    <Spin spinning={loading}>
                        <Row gutter={24}>
                            <Col xxl={24} xl={24} lg={24} md={24} sm={24} xs={24}>
                                {isSearching ? (
                                    <Card bordered={false}>
                                        <CardList
                                            onSearchData={async (pageSize, current, value) => {
                                                await loadAllData(pageSize, current, '');
                                            }}
                                            currentPage={currentPage}
                                            setCurrentPage={(page: number) => setCurrentPage(page)}
                                            searchKey={searchKey}
                                            records={cardRecords}
                                            recordsCount={cardCount}
                                        />
                                    </Card>
                                ) : (
                                    <Card
                                        bordered={false}
                                        tabList={operationTabList}
                                        activeTabKey={tabKey}
                                        onTabChange={async (_tabKey: string) => {
                                            setTabKey(_tabKey as tabKeyType);
                                        }}
                                        tabBarExtraContent={
                                            <ProFormSelect
                                                name="sex"
                                                placeholder="选择影片类型"
                                                fieldProps={{
                                                    labelInValue: true,
                                                }}
                                                style={{
                                                    position: "relative",
                                                    top: "12px"
                                                }}
                                                // @ts-ignore
                                                onChange={(value) => loadAllData(10000, 0, value ? value.label : '')}
                                                valueEnum={{
                                                    movie: '电影',
                                                    tv: '剧集',
                                                }}
                                            />
                                        }
                                    >
                                        {renderChildrenByTabKey(tabKey)}
                                    </Card>
                                )}
                            </Col>
                        </Row>
                    </Spin>
                </Content>
            </Layout>
        </>
    );
};

export default FilmTelevision;
